<?php
class Zend_View_Helper_ShortUrl {
	
	public function shortUrl($url, $length = null)
	{
		if (!isset($length))
		{
			$length = 50;
		}
		$chunkLength = $length / 2;
		$url = str_replace('http://', '', $url);
		$url = str_replace('https://', '', $url);
		
		if (strlen($url) <= $length) {
			return $url;
		}
		
		$startChunk = $this->_shortString($url, $chunkLength);
		$endChunk = $this->_shortString($url, $chunkLength, true);
		
		return $startChunk . '..' . $endChunk;
	}
	
	protected function _shortString($string, $length, $reverse = false) 
	{
		$stopChars = array(' ', '/', '&');
		$acceptableShortness = $length * 0.80;
		
		if ($reverse)
		{
			$string = strrev($string);
		}
		$shortString = '';
		for ($i = 0; $i < $length - 1; $i++)
		{
			$shortString .= $string[$i];
			if ($i >= $acceptableShortness && in_array($string[$i], $stopChars))
			{
				break;
			}
		}
		
		if ($reverse)
		{
			$shortString = strrev($shortString);
		}
		
		return $shortString;
	}
}